package lumis.service.wsrp.consumer.doui;

import java.util.List;

import lumis.doui.control.ControlContainer;
import lumis.doui.control.IControl;
import lumis.doui.control.dropdownlist.DropDownListControl;
import lumis.portal.PortalException;
import lumis.portal.UnexpectedException;
import lumis.service.wsrp.common.WSRPVersionFromTo;
import lumis.util.XmlUtil;

import org.w3c.dom.Node;

import com.sun.portal.wsrp.common.WSRPMBeanException;
import com.sun.portal.wsrp.consumer.admin.mbeans.WSRPConsumer;

/**
 * {@link DropDownListControl} that adds as its options all supported versions
 * reported by the WSDL producer. Uses the {@link WSRPVersionFromTo} enum to get
 * a localizable string that can be shown to user.
 * 
 * @version $Revision: 11180 $ $Date: 2009-12-04 18:13:02 -0200 (Fri, 04 Dec 2009) $
 * @since 5.5.0
 */
public class ConsumerConfigurationInterfaceDropDownListControl extends DropDownListControl
{
	@Override
	public void init(Node controlDefinitionNode, ControlContainer controlContainer, IControl parentControl) throws PortalException
	{
		super.init(controlDefinitionNode, controlContainer, parentControl);

		// gets the producer's wsdl address
		String wsdlUrl = douiContext.getRequest().getParameter(
				ConsumerConfigurationInterfaceProcessActionHandler.WSDL_URL_PARAMETER_NAME);
		if (wsdlUrl == null || "".equals(wsdlUrl))
			return;

		WSRPConsumer consumer = new WSRPConsumer();

		// gets the producer's supported versions
		List<String> supportedVersions;
		try
		{
			supportedVersions = consumer.getSupportedVersions(wsdlUrl);
		}
		catch (WSRPMBeanException e)
		{
			throw new UnexpectedException(e);
		}

		// adds supported versions reported by producer as its options
		for (String supportedVersion : supportedVersions)
		{
			// try to get a WSRPVersionFromTo by value
			WSRPVersionFromTo versionFromTo;
			try
			{
				versionFromTo = WSRPVersionFromTo.getFromValue(supportedVersion);
			}
			catch (IllegalArgumentException e)
			{
				versionFromTo = null;
			}

			if (versionFromTo != null)
			{
				Node optionNode = XmlUtil.addTextNode(controlDefinitionNode, "option", localize(versionFromTo.getLocalizableName()));
				XmlUtil.addNodeAttr(optionNode, "value", versionFromTo.getValue());
			}
			else
			{
				Node optionNode = XmlUtil.addTextNode(controlDefinitionNode, "option", supportedVersion);
				XmlUtil.addNodeAttr(optionNode, "value", supportedVersion);
			}
		}
	}
}
